package com.haojin.exer;

import org.junit.Test;

/**
 * @author .29.
 * @create 2022-04-03 20:34
 */
/*
获取一个字符串在另一个字符串中出现的次数。
  比如：获取“ab”在“abkkcadkabjebfkabkskab”中出现的次数
 */
public class StringDemo1 {

    public int Count(String mainStr,String subStr){
        int mainLength = mainStr.length();
        int subLength = subStr.length();
        int count = 0;
        int index = 0;
        if( mainLength >= subLength){
            //方式一
//            while((index = mainStr.indexOf(subStr)) != -1){
//                count++;
//                mainStr = mainStr.substring(index + subStr.length());
//            }return count;
            //对方式一的改进
            while((index = mainStr.indexOf(subStr,index)) != -1){
                count++;
                index += subLength;
            }return count;
        }else return 0;
    }

    @Test
    public void getCount(){
        String mainStr = "abkkcadkabjebfkabkskab";
        String subStr = "ab";
        int count = Count(mainStr,subStr);
        System.out.println(count);
    }

}
